package com.kcsoft.service.impl;

import com.kcsoft.mapper.UserMapper;
import com.kcsoft.pojo.User;
import com.kcsoft.service.UserService;
import com.kcsoft.utils.Md5Util;
import com.kcsoft.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(String username, String password) {
        userMapper.add(username,password);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(String username, String stuId, String password, String name) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String uname = (String) claims.get("username");
        User user = userMapper.findByUsername(uname);
        if (stuId != null)
            user.setStuId(stuId);
        if (password != null) {
            password = Md5Util.genPwd(password);
            user.setPassword(password);
        }
        if (username != null)
            user.setUsername(username);
        if (name != null)
            user.setName(name);
        userMapper.update(user);
    }

    @Override
    public User findById(Integer userId) {
        return userMapper.findById(userId);
    }
}
